#include "gagent_def.h"


uint16_t gagent_parse_rem_len(const uint8_t* buf)
{
	uint16_t multiplier = 1;
	uint16_t value = 0;
	uint8_t digit;
		
	buf++;	// skip "flags" byte in fixed header

	do {
		digit = *buf;
		value += (digit & 0x7F) * multiplier;
		multiplier *= 0x80;
		buf++;
	} while ((digit & 0x80) != 0);

	return value;
}

uint8_t gagent_num_rem_len_bytes(const uint8_t* buf)
{
	uint8_t num_bytes = 1;
		
	if ((buf[1] & 0x80) == 0x80) {
		num_bytes++;
		if ((buf[2] & 0x80) == 0x80) {
			num_bytes ++;
			if ((buf[3] & 0x80) == 0x80) {
				num_bytes ++;
			}
		}
	}
	return num_bytes;
}


int gagent_get_one_packet(char *packet, int *packet_len, int remain_len)
{
	char			*index;
	uint16_t		len;
	uint8_t			length_len;
	
	if(packet == NULL || packet_len == NULL || remain_len <= 0) 
	    return -1;

	index = packet;

	len = gagent_parse_rem_len((const uint8_t *)index + 3);
	length_len = gagent_num_rem_len_bytes((const uint8_t*)index + 3);

	*packet_len = 4 + len + length_len;
	
//	memset(packet, 0, BUF_LEN);
//	memcpy(packet, index, *packet_len);

//	memcpy(lan->recv_buf, lan->recv_buf+*packet_len, lan->recv_len-*packet_len);
	
	return 0;
}
